<template>
  <el-dialog
      title="办理入住"
      v-if="modelValue"
      :model-value="modelValue"
      width="750px"
      append-to-body
      @close="handleClose"
  >
    <div class="app-container">
      <!-- 步骤条 -->
      <el-steps :active="activeStep" finish-status="success" simple style="margin-bottom: 20px">
        <el-step title="选择房间"></el-step>
        <el-step title="配置租金信息"></el-step>
      </el-steps>

      <el-form ref="checkInFormRef" :model="checkInForm" :rules="rules" label-width="100px">
        <!-- 第一步：房间选择 -->
        <div v-show="activeStep === 0">
          <el-form-item label="房间搜索" prop="name">
            <el-input
                v-model="name"
                placeholder="可搜索房间号"
                clearable>
              <template #append>
                <el-button @click="handleSearch">
                  <el-icon style="margin-right: 5px;">
                    <Search/>
                  </el-icon>
                </el-button>
              </template>
            </el-input>
          </el-form-item>

          <!-- 房间列表展示 -->
          <el-table
              v-loading="loading"
              :data="roomList"
              highlight-current-row
              @current-change="handleRoomSelect"
              border
              stripe
              style="width: 100%; margin-bottom: 15px;">
            <el-table-column type="index" width="50" align="center"/>
            <el-table-column label="房间号" prop="name" min-width="100"/>
            <el-table-column label="楼栋" prop="buildingName" min-width="100"/>
            <el-table-column label="操作" width="120" align="center">
              <template #default="scope">
                <el-button
                    type="primary"
                    size="mini"
                    @click="selectRoom(scope.row)">
                  选择
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页器 -->
          <pagination
              v-if="total > 0"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryParams.pageNum"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="queryParams.pageSize"
              :total="total">
          </pagination>
        </div>

        <!-- 第二步：租金信息配置 -->
        <div v-show="activeStep === 1">
          <!-- 已选房间信息展示 -->
          <el-alert
              v-if="selectedRoom"
              title="已选房间信息"
              type="info"
              :description="`${selectedRoom.name || ''} - ${selectedRoom.buildingName || ''} ${selectedRoom.typeName || ''}`"
              show-icon
              :closable="false"
              style="margin-bottom: 20px"
          />

          <!-- 租金和租期信息 -->
          <el-divider content-position="left">租金与租期信息</el-divider>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="入住周期" required>
                <el-row>
                  <el-col :span="11">
                    <el-form-item prop="checkInStart">
                      <el-date-picker
                          v-model="checkInForm.checkInStart"
                          type="date"
                          placeholder="请选择开始时间"
                          style="width: 100%;"
                          @change="handleStartDateChange"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="2" style="text-align: center;">
                    <span>-</span>
                  </el-col>
                  <el-col :span="11">
                    <el-form-item prop="checkInEnd">
                      <el-date-picker
                          v-model="checkInForm.checkInEnd"
                          type="date"
                          placeholder="请选择结束时间"
                          style="width: 100%;"
                          @change="handleEndDateChange"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-radio-group v-model="rentPeriod" @change="handleQuicklyDate" :disabled="!checkInForm.checkInStart">
                <el-radio-button :label="1">1月</el-radio-button>
                <el-radio-button :label="3">3月</el-radio-button>
                <el-radio-button :label="6">6月</el-radio-button>
                <el-radio-button :label="12">12月</el-radio-button>
              </el-radio-group>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="租金" required>
                <el-row>
                  <el-col :span="8">
                    <el-form-item prop="rentObject.rentCollectCycle" label-width="0">
                      <el-select v-model="checkInForm.rentObject.rentCollectCycle">
                        <el-option label="月租金" value="1"></el-option>
                        <el-option label="日租金" value="2"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="16">
                    <el-form-item prop="rentObject.rent" label-width="0">
                      <el-input v-model="checkInForm.rentObject.rent" placeholder="请输入租金"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="押金" prop="rentObject.deposit">
                <el-input v-model="checkInForm.rentObject.deposit" placeholder="请输入押金"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="支付方式" prop="rentObject.rentType">
                <el-select v-model="checkInForm.rentObject.rentType" placeholder="请选择支付时间">
                  <el-option label="每1月" value="1"></el-option>
                  <el-option label="每2月" value="2"></el-option>
                  <el-option label="每3月" value="3"></el-option>
                  <el-option label="每半年" value="5"></el-option>
                  <el-option label="每一年" value="6"></el-option>
                  <el-option label="一次性" value="7"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="checkInForm.remark" placeholder="请输入备注"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button v-if="activeStep > 0" @click="prevStep">上一步</el-button>
        <el-button v-if="activeStep < 1" type="primary" @click="nextStep" :disabled="!selectedRoom">下一步</el-button>
        <el-button v-if="activeStep === 1" type="primary" :loading="loading" @click="submitForm">确 定</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import {listAvailableRooms} from "@/api/room/room";
import {getInfo} from "@/api/room/preregister";

export default {
  name: "CheckInDialog",
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    registerId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      loading: false,
      // 当前步骤
      activeStep: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: ''
      },
      name: '',
      // 房间列表
      roomList: [],
      // 已选择的房间
      selectedRoom: null,
      // 总条数
      total: 0,
      // 租期快速选择
      rentPeriod: 1,
      // 表单数据
      checkInForm: {
        id: null,
        roomId: null,
        checkInStart: new Date(),
        checkInEnd: null,
        rentObject: {
          rentCollectCycle: '1', // 月租金
          rent: '',
          deposit: '',
          rentType: '1', // 每1月
        },
        remark: ''
      },
      // 表单校验规则
      rules: {
        roomId: [
          {required: true, message: "房间不能为空", trigger: "change"}
        ],
        checkInStart: [
          {required: true, message: "开始时间不能为空", trigger: "change"}
        ],
        checkInEnd: [
          {required: true, message: "结束时间不能为空", trigger: "change"}
        ],
        'rentObject.rent': [
          {required: true, message: "租金不能为空", trigger: "blur"},
          {pattern: /^(0|([1-9][0-9]*))?(.\d{1,2})?$/, message: "请输入正确的租金", trigger: ["blur", "change"]}
        ],
        'rentObject.deposit': [
          {required: true, message: "押金不能为空", trigger: "blur"},
          {pattern: /^(0|([1-9][0-9]*))?(.\d{1,2})?$/, message: "请输入正确的押金", trigger: ["blur", "change"]}
        ]
      }
    };
  },
  watch: {
    modelValue(val) {
      if (val) {
        this.reset();
        this.checkInForm.id = this.registerId;
        this.getAvailableRooms();
        
        // 获取预登记详情，检查是否已有房间
        this.loading = true;
        getInfo(this.registerId).then(response => {
          this.loading = false;
          if (response.code === 200) {
            const preRegisterInfo = response.data || {};
            
            // 如果预登记已有房间，直接设置房间并跳到第二步
            if (preRegisterInfo.room && preRegisterInfo.room.id) {
              this.selectedRoom = preRegisterInfo.room;
              this.checkInForm.roomId = preRegisterInfo.room.id || preRegisterInfo.room.roomId;
              this.activeStep = 1; // 直接跳到第二步
            } else if (preRegisterInfo.roomId && preRegisterInfo.roomId > 0) {
              // 如果只有roomId且不为-1或负数，需要从房间列表中找到对应房间
              this.checkInForm.roomId = preRegisterInfo.roomId;
              
              // 等待房间列表加载完成后找到对应房间
              this.$nextTick(() => {
                const room = this.roomList.find(r => (r.id === preRegisterInfo.roomId || r.roomId === preRegisterInfo.roomId));
                if (room) {
                  this.selectedRoom = room;
                  this.activeStep = 1; // 直接跳到第二步
                }
              });
            }
          }
        }).catch(error => {
          this.loading = false;
          console.error("获取预登记详情失败:", error);
        });
      }
    }
  },
  methods: {
    // 获取可用房间列表
    getAvailableRooms() {
      this.loading = true;

      const params = {
        ...this.queryParams
      };
      if (this.name) {
        params.name = this.name;
      }

      listAvailableRooms(params).then(response => {
        this.loading = false;
        if (response.code === 200) {
          this.roomList = response.rows || [];
          this.total = response.total || 0;
        } else {
          this.$modal.msgError(response.msg || "获取房间列表失败");
          this.roomList = [];
          this.total = 0;
        }
      }).catch(error => {
        this.loading = false;
        console.error("获取可用房间列表失败:", error);
        this.$modal.msgError("获取房间列表失败");
      });
    },

    // 搜索房间
    handleSearch() {
      this.queryParams.pageNum = 1;
      this.getAvailableRooms();
    },

    // 页码改变
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getAvailableRooms();
    },

    // 每页条数改变
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.queryParams.pageNum = 1;
      this.getAvailableRooms();
    },

    // 选择房间
    selectRoom(room) {
      this.selectedRoom = room;
      this.checkInForm.roomId = room.id || room.roomId;
      this.nextStep();
    },

    // 处理行选择
    handleRoomSelect(row) {
      if (row) {
        this.selectedRoom = row;
        this.checkInForm.roomId = row.id || row.roomId;
      } else {
        this.selectedRoom = null;
        this.checkInForm.roomId = null;
      }
    },

    // 下一步
    nextStep() {
      if (this.activeStep === 0 && !this.checkInForm.roomId) {
        this.$modal.msgWarning('请先选择房间');
        return;
      }
      this.activeStep++;
    },

    // 上一步
    prevStep() {
      this.activeStep--;
    },

    // 开始日期变更
    handleStartDateChange(date) {
      if (date && this.checkInForm.checkInEnd) {
        if (date > this.checkInForm.checkInEnd) {
          this.checkInForm.checkInEnd = null;
        }
      }
    },

    // 结束日期变更
    handleEndDateChange(date) {
      if (date && this.checkInForm.checkInStart) {
        if (date < this.checkInForm.checkInStart) {
          this.$modal.msgWarning('结束日期不能早于开始日期');
          this.checkInForm.checkInEnd = null;
        }
      }
    },

    // 快速设置租期
    handleQuicklyDate(months) {
      if (!this.checkInForm.checkInStart) {
        this.$modal.msgWarning('请先选择开始日期');
        return;
      }

      const startDate = new Date(this.checkInForm.checkInStart);
      let endDate = new Date(startDate);
      endDate.setMonth(startDate.getMonth() + months);
      endDate.setDate(endDate.getDate() - 1); // 减去一天，比如1月1日到1月31日

      this.checkInForm.checkInEnd = endDate;
    },

    // 提交表单
    submitForm() {
      this.$refs.checkInFormRef.validate(valid => {
        if (valid) {
          this.loading = true;

          // 将日期格式化为字符串
          const formatDate = (date) => {
            if (!date) return '';
            const d = new Date(date);
            const year = d.getFullYear();
            const month = String(d.getMonth() + 1).padStart(2, '0');
            const day = String(d.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
          };

          // 触发提交事件，由父组件处理API调用
          this.$emit('submit', {
            id: this.checkInForm.id,
            roomId: this.checkInForm.roomId,
            checkInStart: formatDate(this.checkInForm.checkInStart),
            checkInEnd: formatDate(this.checkInForm.checkInEnd),
            rentObject: this.checkInForm.rentObject,
            remark: this.checkInForm.remark
          });

          // 父组件需要处理loading的结束
          // 这里不关闭对话框，由父组件决定是否关闭
        }
      });
    },

    // 关闭对话框
    handleClose() {
      this.$emit('update:modelValue', false);
    },

    // 重置表单
    reset() {
      // 重置步骤
      this.activeStep = 0;

      // 重置分页参数
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        name: ''
      };
      this.name = '';

      // 重置选中房间
      this.selectedRoom = null;

      // 重置表单
      this.checkInForm = {
        id: this.registerId,
        roomId: null,
        checkInStart: new Date(),
        checkInEnd: null,
        rentObject: {
          rentCollectCycle: '1', // 月租金
          rent: '',
          deposit: '',
          rentType: '1', // 每1月
        },
        remark: ''
      };

      // 重置租期选择
      this.rentPeriod = 1;

      // 如果表单引用存在，重置验证
      if (this.$refs.checkInFormRef) {
        this.$refs.checkInFormRef.resetFields();
      }
    }
  }
};
</script>

<style scoped>
.dialog-footer {
  margin-top: 20px;
  text-align: right !important;
}
</style>
